'''
This script is used to send saved packets one at a time.
Packets must be in pcap-format in order to work.
Makes it easier to determine which packages cause results.
'''
import socket
import struct
import sys


def main(args):

    try:
        fl = open(args[0], 'r')
    except:
        print "Couldn't open the specified file."
        return

    header = fl.read(8)
    reverse = False

    if "\xa1\xb2\xc3\xd4" in header and "\x00\x02\x00\x04" in header:
        reverse = False
    elif "\xd4\xc3\xb2\xa1" in header and "\x02\x00\x04\x00" in header:
        reverse = True
    else:
        print "Not a pcap-file."
        return

    try:
        sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
        sock.bind((args[1],0))
    except:
        print "Error: socket could not be opened"
        return

    fl.seek(24)
    header = ""
    data = ""
    pLen = 0
    counter = 1

    var = raw_input('\nPress enter to start sending packages.\n')

    while True:

        try:
            header = fl.read(16)

            if reverse:
                header = (header[0:4][::-1]+
                          header[4:8][::-1]+
                          header[8:12][::-1]+
                          header[12:16][::-1])

            if len(header)!=16: break

            pLen = struct.unpack('>I', header[8:12])[0]

            data = fl.read(pLen)

            print "Sending packet #{} with length: {}\n".format(counter,pLen)
            try:
                sock.send(data)
            except:
                print "Package could not be send."
            var = raw_input('Press enter to continue...')
            print ""
            counter += 1

        except KeyboardInterrupt:
            print "\nInterrupted.. Exiting safely."
            break

    print "End of file, exiting."
    

if __name__=="__main__":
    main(sys.argv[1:])
